#!/usr/bin/env python3
"""调试1688页面结构"""

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def debug_page_structure():
    """调试页面结构"""
    url = "https://www.1688.com/zw/page.html?hpageId=old-sem-pc-list&keywords=%E9%85%92%E5%BA%97%E7%94%A8%E6%96%B9%E5%B7%BE%E7%BA%B8&cosite=&location=&trackid=&spm=a312h.2018_new_sem.dh_004.submit&keywordid=&bt=&exp=pcSemFumian%3AC%3BpcCpxGuessExp%3AB%3Bbangdan%3AB%3Bqztf%3AE%3BpcSemWwClick%3AA%3Basst%3AE%3BpcSemDownloadPlugin%3AA&ptid=&sortType=&descendOrder=&province=&city=&priceStart=&priceEnd=&dis=&provinceValue=%E6%89%80%E5%9C%A8%E5%9C%B0%E5%8C%BA&p_rs=true"
    
    # 设置浏览器选项（使用Chromium）
    options = Options()
    
    # 指定Chromium二进制文件路径
    options.binary_location = '/usr/bin/chromium'
    
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('--disable-blink-features=AutomationControlled')
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    options.add_argument('--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
    
    # 指定ChromeDriver路径
    from selenium.webdriver.chrome.service import Service
    service = Service('/usr/bin/chromedriver')
    driver = webdriver.Chrome(service=service, options=options)
    
    try:
        print(f"访问URL: {url}")
        driver.get(url)
        time.sleep(5)
        
        print(f"当前页面标题: {driver.title}")
        print(f"当前URL: {driver.current_url}")
        
        # 查找所有可能的商品容器
        container_selectors = [
            '.offer-item',
            '.sm-offer-item', 
            '[class*="offer"][class*="item"]',
            '.item',
            '[class*="item"]',
            '.product-item',
            '.goods-item',
            '[data-offer-id]'
        ]
        
        print("\n=== 查找商品容器 ===")
        for selector in container_selectors:
            try:
                elements = driver.find_elements(By.CSS_SELECTOR, selector)
                print(f"{selector}: 找到 {len(elements)} 个元素")
                if elements:
                    # 分析第一个元素的结构
                    first_element = elements[0]
                    print(f"  第一个元素的class: {first_element.get_attribute('class')}")
                    print(f"  第一个元素的HTML片段: {first_element.get_attribute('outerHTML')[:200]}...")
            except Exception as e:
                print(f"{selector}: 错误 - {e}")
        
        # 如果找到了商品容器，分析其内部结构
        product_containers = driver.find_elements(By.CSS_SELECTOR, '.offer-item, .sm-offer-item, [class*="offer"][class*="item"]')
        if product_containers:
            print(f"\n=== 分析第一个商品容器的内部结构 ===")
            first_container = product_containers[0]
            
            # 查找标题相关元素
            title_selectors = [
                'a[title]',
                '.offer-title',
                '.title',
                'h3',
                'h4',
                '[class*="title"]',
                '[class*="name"]'
            ]
            
            print("\n--- 标题元素 ---")
            for selector in title_selectors:
                try:
                    elements = first_container.find_elements(By.CSS_SELECTOR, selector)
                    for i, elem in enumerate(elements[:3]):  # 只显示前3个
                        title_text = elem.get_attribute('title') or elem.text.strip()
                        print(f"{selector}[{i}]: {title_text[:100]}")
                except Exception as e:
                    print(f"{selector}: 错误 - {e}")
            
            # 查找价格相关元素
            price_selectors = [
                '.price',
                '.offer-price',
                '[class*="price"]',
                '[class*="Price"]',
                '.money',
                '[class*="money"]'
            ]
            
            print("\n--- 价格元素 ---")
            for selector in price_selectors:
                try:
                    elements = first_container.find_elements(By.CSS_SELECTOR, selector)
                    for i, elem in enumerate(elements[:3]):
                        price_text = elem.text.strip()
                        if price_text:
                            print(f"{selector}[{i}]: {price_text}")
                except Exception as e:
                    print(f"{selector}: 错误 - {e}")
            
            # 查找销量相关元素
            sales_selectors = [
                '.sale',
                '.sales',
                '.trade',
                '[class*="sale"]',
                '[class*="trade"]',
                '[class*="sold"]',
                '[class*="成交"]'
            ]
            
            print("\n--- 销量元素 ---")
            for selector in sales_selectors:
                try:
                    elements = first_container.find_elements(By.CSS_SELECTOR, selector)
                    for i, elem in enumerate(elements[:3]):
                        sales_text = elem.text.strip()
                        if sales_text:
                            print(f"{selector}[{i}]: {sales_text}")
                except Exception as e:
                    print(f"{selector}: 错误 - {e}")
            
            # 输出完整的HTML结构用于分析
            print("\n--- 第一个商品容器的完整HTML ---")
            print(first_container.get_attribute('outerHTML')[:1000] + "...")
        
        # 保存页面源码用于离线分析
        with open('1688_page_source.html', 'w', encoding='utf-8') as f:
            f.write(driver.page_source)
        print("\n页面源码已保存到 1688_page_source.html")
        
    except Exception as e:
        print(f"调试过程中出错: {e}")
    
    finally:
        driver.quit()


if __name__ == "__main__":
    debug_page_structure()